package com.example.auth;

import io.vertx.core.AbstractVerticle;
import io.vertx.core.Promise;
import io.vertx.core.Vertx;
import io.vertx.core.http.HttpServer;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.handler.BodyHandler;
import io.vertx.ext.web.handler.SessionHandler;
import io.vertx.ext.web.sstore.LocalSessionStore;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Main Verticle to start the HTTP server and configure routes for Waffle-based authentication.
 */
public class MainVerticle extends AbstractVerticle {

    private static final Logger logger = LoggerFactory.getLogger(MainVerticle.class);
    private static final int DEFAULT_PORT = 8080;

    @Override
    public void start(Promise<Void> startPromise) throws Exception {
        logger.info("Starting Waffle authentication server...");

        HttpServer server = vertx.createHttpServer();
        Router router = Router.router(vertx);

        // Session handler is required for Waffle to maintain security context across requests
        router.route().handler(SessionHandler.create(LocalSessionStore.create(vertx)));
        router.route().handler(BodyHandler.create());

        WaffleAuthHandler authHandler = new WaffleAuthHandler();

        // All routes under /protected require authentication
        router.route("/protected/*").handler(authHandler);

        router.get("/protected/resource").handler(ctx -> {
            String user = ctx.session().get("user");
            logger.info("Accessing protected resource as user: {}", user);
            ctx.response()
               .putHeader("Content-Type", "text/html; charset=utf-8")
               .end("<h1>Welcome, " + user + "</h1><p>You have accessed a protected resource.</p>");
        });
        
        // Unprotected route
        router.get("/").handler(ctx -> {
            String html = buildIndexPage();
            ctx.response()
                .putHeader("Content-Type", "text/html; charset=utf-8")
                .end(html);
        });

        int port = config().getInteger("http.port", DEFAULT_PORT);
        String host = config().getString("http.host", "0.0.0.0");

        server.requestHandler(router)
            .listen(port, host)
            .onSuccess(result -> {
                logger.info("Server started successfully on http://{}:{}", host, port);
                logger.info("Access http://{}:{}/protected/resource to trigger authentication", host, port);
                startPromise.complete();
            })
            .onFailure(cause -> {
                logger.error("Server startup failed", cause);
                startPromise.fail(cause);
            });
    }
    

    
    /**
     * 构建主页HTML
     */
    private String buildIndexPage() {
        // 主页面HTML
        String mainPageHtml = "<!DOCTYPE html>\n" +
            "<html lang=\"zh-CN\">\n" +
            "<head>\n" +
            "    <meta charset=\"UTF-8\">\n" +
            "    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n" +
            "    <title>Windows身份验证系统</title>\n" +
            "    <style>\n" +
            "        body { font-family: Arial, sans-serif; margin: 40px; background-color: #f5f5f5; }\n" +
            "        .container { max-width: 800px; margin: 0 auto; background: white; padding: 30px; border-radius: 8px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); }\n" +
            "        h1 { color: #333; text-align: center; margin-bottom: 30px; }\n" +
            "        .info-box { background: #e7f3ff; padding: 20px; border-radius: 5px; margin: 20px 0; border-left: 4px solid #2196F3; }\n" +
            "        .button { display: inline-block; padding: 12px 24px; background: #2196F3; color: white; text-decoration: none; border-radius: 5px; margin: 10px 5px; }\n" +
            "        .button:hover { background: #1976D2; }\n" +
            "        .status { margin: 20px 0; padding: 15px; border-radius: 5px; }\n" +
            "        .success { background: #d4edda; color: #155724; border: 1px solid #c3e6cb; }\n" +
            "        .error { background: #f8d7da; color: #721c24; border: 1px solid #f5c6cb; }\n" +
            "    </style>\n" +
            "</head>\n" +
            "<body>\n" +
            "    <div class=\"container\">\n" +
            "        <h1>Windows身份验证系统</h1>\n" +
            "        <div class=\"info-box\">\n" +
            "            <h3>系统功能</h3>\n" +
            "            <ul>\n" +
            "                <li>自动NTLM身份验证</li>\n" +
            "                <li>获取Windows域用户信息</li>\n" +
            "                <li>无需手动输入用户名密码</li>\n" +
            "                <li>支持域用户和本地用户</li>\n" +
            "            </ul>\n" +
            "        </div>\n" +
            "        \n" +
            "        <div style=\"text-align: center;\">\n" +
            "            <a href=\"/auth\" class=\"button\">开始身份验证</a>\n" +
            "            <a href=\"/health\" class=\"button\">系统状态</a>\n" +
            "        </div>\n" +
            "        \n" +
            "        <div id=\"status\" class=\"status\" style=\"display: none;\"></div>\n" +
            "    </div>\n" +
            "    \n" +
            "    <script>\n" +
            "        // 检查身份验证状态\n" +
            "        function checkAuthStatus() {\n" +
            "            fetch('/api/user-info')\n" +
            "                .then(response => response.json())\n" +
            "                .then(data => {\n" +
            "                    const statusDiv = document.getElementById('status');\n" +
            "                    if (data.authenticated) {\n" +
            "                        statusDiv.className = 'status success';\n" +
            "                        statusDiv.innerHTML = '<h4>已认证用户</h4><p>用户名: ' + data.username + '</p><p>域: ' + data.domain + '</p>';\n" +
            "                        statusDiv.style.display = 'block';\n" +
            "                    }\n" +
            "                })\n" +
            "                .catch(err => console.log('未认证或认证失败'));\n" +
            "        }\n" +
            "        \n" +
            "        // 页面加载时检查状态\n" +
            "        window.onload = checkAuthStatus;\n" +
            "    </script>\n" +
            "</body>\n" +
            "</html>";
        
        return mainPageHtml;
    }
    
    /**
     * 应用程序入口点
     * 提供传统的main方法来启动Vert.x应用程序
     */
    public static void main(String[] args) {
        // 创建Vertx实例
        Vertx vertx = Vertx.vertx();
        
        // 部署MainVerticle
        vertx.deployVerticle(new MainVerticle())
            .onSuccess(id -> {
                System.out.println("应用程序启动成功！部署ID: " + id);
                System.out.println("访问 http://localhost:8080 查看应用程序");
            })
            .onFailure(cause -> {
                System.err.println("应用程序启动失败: " + cause.getMessage());
                cause.printStackTrace();
                System.exit(1);
            });
    }
}